package com.itheima.web.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.db.Admin;
import com.itheima.web.manager.AdminManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author 请不要叫我高司令
 * @Date 2022/3/24 18:22
 * @Version 1.0
 */

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminManager adminManager;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
  // 1、获取请求头的token
        String token = request.getHeader("Authorization");
        //没取到，就返回401
        if (StrUtil.isEmpty(token)) {
            response.setStatus(401);
            return false;
        }

        //查询redis中是否还有登录状态，没取到，就返回401
        Admin admin = adminManager.findAdminByToken(token);
        if (ObjectUtil.isEmpty(admin)) {
            response.setStatus(401);
            return false;
        }

        //将admin绑定当前线程
        AdminHolder.set(admin);

        //放行
        return true;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
